package main

import (
    "fmt"
    "log"
    "net/http"
    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
    CheckOrigin: func(r *http.Request) bool { return true },
}
var clients = make(map[*websocket.Conn]bool)
func handleConnection(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println("Error while upgrading connection:", err)
        return
    }
    clients[conn] = true
    defer conn.Close()

    for {
        var msg map[string]interface{}
        err := conn.ReadJSON(&msg)
        if err != nil {
            log.Println("Error while reading message:", err)
            break
        }

        // Broadcast the received message to all connected clients
        // Here you should manage multiple connections and handle the broadcast appropriately
        // For simplicity, we'll assume a single connection scenario

        log.Printf("Received message: %v", msg)
        // Broadcast message to all clients or to a specific client
        for client := range clients {
			err := client.WriteJSON(msg)
			if err != nil {
				fmt.Println("Error writing message:", err)
				client.Close()
				delete(clients, client)
			}
		}
    }
}

func main() {
    http.HandleFunc("/ws", handleConnection)

    log.Println("WebSocket server started at ws://localhost:8080/ws")
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("Error while starting server:", err)
    }
}

